<template>
  <div class="myInput">
    <el-form :inline="true" v-model="metaData" class="search-form">
      <el-form-item label="" class="form-input">
        <el-cascader v-model="metaData.searchType" :props="{ checkStrictly: true }" placeholder="全部" load
          :options="optionsType" clearable filterable @change="hidePanelDom" ref="panelDom"></el-cascader>
      </el-form-item>
    </el-form>
    <el-autocomplete class="inline-input" v-model="state" :clearable="true" :fetch-suggestions="querySearch"
      placeholder="加入节点" :trigger-on-focus="false" :popper-append-to-body="isPa" @select="handleSelect"
      @focus="focusInput" @clear="clearInput" :debounce="500">
      <!-- eslint-disable-next-line vue/no-unused-vars -->
      <template v-for="item in restaurants" slot-scope="{item}">
        <div v-if="lastRes.length > 0" :key="item.id" class="myOption" @click="selectedValue">
          <span class="flex-center">{{item.ontology_name}}</span>
          <el-tooltip class="item" effect="dark" :content="item.value" placement="top-start">
            <p>{{item.value}}</p>
          </el-tooltip>
        </div>
      </template>
    </el-autocomplete>
    <!-- <div class="join" @click="join()">加入</div> -->
  </div>

</template>

<script>
  import {
    mapState,
    mapMutations
  } from 'vuex';
  export default {
    name: "my-input",
    // components: {
    //   IconPark
    // },
    props: {
      isPa: {
        type: Boolean,
        default: false
      }
    },
    data() {
      return {
        count: true,
        initDom: [],
        restaurants: [],
        state: null,
        lastRes: [],
        dataList: [],
        results: [],
        metaData: {
          searchType: [],
        },
        optionsType: [],
        entityIds: ''
        // cbFun: null,
      };
    },
    computed: {
      ...mapState({
        allNodesId: state => state.ontologyModel.graphDatas,
        projectId: state => state.knowledgeMap.projectMsg.projectId
      }),
    },
    watch: {
      '$store.state.knowledgeMap.projectMsg.projectId': {
        handler(val, old) {
          if (val !== old) {
            this.mapTree();
          }
        },
        deep: true,
        immediate: true
      },
      state(newVal, oldVal) {
        if (newVal) {
          this.focusInput();
          // this.querySearch(newVal, this.cbFun);
        }
      },
    },
    methods: {
      async mapTree() {
        let params = {
          projectId: this.$store.state.knowledgeMap.projectMsg.projectId
        }
        let res = await this.$axios.post(this.$api.knowledgeMap.mapTree, params)
        const {
          data,
          message,
          code
        } = res.data;
        if (code == 200) {
          this.hideSubPanelData(data);
          this.optionsType = data;
        } else {
          this.$message.warning(message);
        }
      },

      hideSubPanelData(obj) {
        if (Array.isArray(obj)) {
          obj.length > 0 && obj.map(item => {
            if (item.children.length === 0) {
              delete item.children;
            } else {
              this.hideSubPanelData(item.children);
            }
          });
        } else {
          this.$message.warning("数据格式出错");
        }
        return obj;
      },

      hidePanelDom(e) {
        if (e.length && this.$refs.panelDom) {
          this.$refs.panelDom.dropDownVisible = false;
        }
      },
      // 点击待选项
      selectedValue(e) {
        this.state = e.target.innerText;
        // this.join();
      },
      // 输入框获得焦点
      focusInput() {
        const inner = document.querySelector(".el-input__inner");
        inner.style.backgroundImage = "none";
      },
      // 输入框失去焦点
      blurInput(e) {
        if (!this.state) {
          // const img = require("../../../../assets/img/search.png");
          const inner = document.querySelector(".el-input__inner");
          // inner.style['background-image'] = `url(${img})`;
          inner.style['background-size'] = "16px";
          inner.style['background-repeat'] = "no-repeat";
          inner.style['background-position'] = "16px";
        }
      },
      // 清空输入框
      clearInput(e) {
        this.state = null;
        this.blurInput();
      },
      async querySearch(queryString, cb) {
        let res = await this.$axios.get(this.$api.knowledgeMap.getSearch, {
          params: {
            projectId: this.projectId,
            keywords: queryString,
            ontologyId: this.metaData.searchType.join()
          }
        });

        var results = [];
        this.initDom = document.getElementsByClassName("el-autocomplete-suggestion__wrap");
        // 承载建议的 dom
        let suggestionList = document.querySelector(".el-autocomplete-suggestion__list");
        // 创建一个承载 暂无搜索结果 的 dom
        let spanDom = document.createElement("span");
        if (this.initDom[0].children.length == 1) {
          spanDom.innerHTML = "暂无搜索结果";
          this.initDom[0].appendChild(spanDom);
        }
        if (res.data.data === "暂无搜索结果") {
          results = [{
            "value": "暂无搜索结果",
          }];
          suggestionList.style.display = "none";
          this.initDom[0].getElementsByTagName("span")[0].style.display = "block";
          cb(results);
          return;
        } else {
          // 每次查询过后需要将待选项列表置空
          console.log("restaurants", this.restaurants);
          this.restaurants = [];
          console.log("aaa2", res.data.data);
          this.initDom[0].getElementsByTagName("span")[0].style.display = "none";
          suggestionList.style.display = "block";

          for (let i = 0; i < res.data.data.length; i++) {
            this.restaurants.push({
              'id': res.data.data[i].id,
              'value': res.data.data[i].name,
              'ontology_name': res.data.data[i].ontology_name,
              // 'project_name': res.data.data[i].project_name,
            })
          }
          var restaurants = this.restaurants;
          console.log("restaurants", this.restaurants);
          results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
          this.lastRes = JSON.parse(JSON.stringify(results));
          console.log('results', results);
          cb(results);
        }
      },
      createFilter(queryString) {
        return (state) => {
          return (state.value.toLowerCase().indexOf(queryString.toLowerCase()) !== -1);
        };
      },

      //点击待选项时触发的方法
      handleSelect(params) {
        this.entityIds = params.id;
        // 判断已添加的数据中是否包含当前点击的实体对象
        // if (this.$store.state.dataList.every(item => item.id !== params.id)) {
        // if (this.$store.state.dataList.every(item => item.id !== params.id)) {
        // 当前点击的实体图谱中已存在
        if (this.allNodesId.Nodes && this.allNodesId.Nodes.every(item => item.entity_id !== params.id)) {
          // this.$store.commit("add_dataList", params);
          this.join();
        } else if (!this.allNodesId.Nodes) {
          this.join();
        } else {
          this.$message({
            type: "warning",
            message: "该实体已添加"
          });
        }
        // }
      },
      async join(params) {
        let oldEntityIdList = [];
        this.allNodesId.Nodes && this.allNodesId.Nodes.forEach(item => {
          oldEntityIdList.push(item.entity_id)
        });
        // console.log("aaaaa", this.entityIds);
        let res = await this.$axios.post(this.$api.knowledgeMap.joinAnalysis, {
          // params: {
          entityId: this.entityIds,
          oldEntityIdList: oldEntityIdList
          // }
        });
        if (res.data && res.data.code === 200) {
          this.$emit("append_graph", res.data.data)
          // this.$eventBus.$emit("append_graph", res.data.data);
          this.state = "";
        }
      },
    }
  };
</script>

<style lang="scss" scoped>
  .myInput {
    display: flex;

    // margin-top: 50px;
    .join {
      width: 66px;
      height: 32px;
      line-height: 32px;
      text-align: center;
      background-color: #4B71EB;
      color: #ffffff;
      float: right;
      border-radius: 2px;
      font-size: 14px;
      margin-top: 3px;
    }

    .join:hover {
      cursor: pointer;
    }

    /deep/.el-form search-form el-form--inline {
      display: flex;
      margin-top: 61px;
    }

    /deep/.el-input_suffix {
      vertical-align: middle;
      display: inline-block;
    }

    .inline-explain {
      margin-top: 20px;
    }

    .search-form {
      /deep/ .el-input__inner {
        height: 40px;
        line-height: 40px;
        width: 100px;
      }

      /deep/ .el-form-item {
        margin-right: 16px;
      }
    }

    .explain {
      width: 50px;
      height: 40px;
      line-height: 40px;
      text-align: center;
      background-color: #008FE0;
      color: #ffffff;
      float: right;
      margin-top: 20px;
    }

    .el-autocomplete {
      width: 160px;
      height: 40px;

      /deep/ .el-autocomplete-suggestion__list li {
        padding: 0 5px;
      }

      // /deep/ .el-autocomplete-suggestion__list li:first-of-type {
      //   color: @tab-active-font-color;
      // }

      .myOption {
        display: flex;
        justify-content: space-between;
        align-items: center;
        text-align: left;

        span {
          height: 24px;
          border-radius: 8px;
        }

        // span:first-of-type {
        //   // min-width: 40px;
        //   height: 24px;
        //   font-size: 12px;
        //   border-radius: 8px;
        //   // background: @tab-bgc-color;

        //   max-width: 74px;
        //   overflow: hidden;
        //   text-overflow: ellipsis;
        //   white-space: nowrap;
        // }

        // span:last-of-type {
        //   // min-width: 87px;
        //   // height: 19px;
        //   width: 88px;
        //   font-size: 12px;
        //   border-radius: 8px;
        //   // background: @tab-bgc-color;

        //   max-width: 74px;
        //   overflow: hidden;
        //   text-overflow: ellipsis;
        //   white-space: nowrap;
        // }

        p {
          flex-grow: 1;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
          padding-left: 10px;
        }
      }

      .flex-center {
        display: flex;
        justify-content: center;
        align-items: center;
        background: #f5f5f5;
      }



      .myOption2 {
        color: #bbb;
        pointer-events: none;
      }

      /deep/ .el-input__inner {
        outline: none;
        border-radius: 2px;
        // background-image: url("../../assets/img/search.png");
        background-repeat: no-repeat;
        background-size: 16px;
        position: relative;
        background-position: 16px;
        height: 40px;
        line-height: 40px;
        width: 160px;
        // background-color: @tab-bgc-color;

        &:focus {
          // border-color: @head-bgc-1;
        }
      }
    }
  }
</style>